package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.ClearingService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.model.MinShengClearingResponseDTO;
import com.lt.test.entity.DTO.ClearingOrderDTO;
import com.lt.test.provider.mapper.ClearingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhengchuan on 2017/5/11.
 */
@Service(version = "1.0.0")
public class ClearingServiceImpl implements ClearingService {
    private static final Logger logger = LoggerFactory.getLogger(ClearingServiceImpl.class);
    @Autowired
    ClearingMapper clearingMapper;

    @Override
    public  Map<String,String> reconciliation(String merId) throws CustomException {
        Map<String, String> result = new HashMap<>(3);

        Map<String, String> params = new HashMap<>(3);
        params.put("merId", merId);
        params.put("date", "20170605");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String now = sdf.format(new Date());
        params.put("now", now);
        Long qrOrderCount = null;
        try {
            qrOrderCount = clearingMapper.getQrOrderCount(params);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取本地订单总数失败"+params);
            throw new CustomException("获取本地订单总数失败");
        }
        Long ynionCount = null;
        try {
            ynionCount = clearingMapper.getYnionCount(params);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取远程订单总数失败"+params);
            throw new CustomException("获取远程订单总数失败");
        }



        if (qrOrderCount != ynionCount) {
            result.put("code","11");
            result.put("msg","订单总数不等");

        }else {
            Long count = null;
            try {
                count = clearingMapper.getClearOrderCount(params);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取对比订单总数失败"+params);
                throw new CustomException("获取对比订单总数失败");
            }
            if (qrOrderCount != count) {
                result.put("code","11");
                result.put("msg","有订单金额不等");
            }else {
                result.put("code","00");
                result.put("msg","对账成功");
            }
        }
        return result;
    }

    @Override
    public List<ClearingOrderDTO> selectNotClearingOrder() throws CustomException {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String now = df.format(new Date());
            return clearingMapper.selectNotClearingOrder(now);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询未清算订单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClearingState(Map<String, String> clearState) throws CustomException {
        String createTime = clearState.get("createTime");
        String[] createTimes =  createTime.split(",");
        clearState.put("createTimes", splitStr(Arrays.asList(createTimes)));
        //0,查询出所有符合条件的订单号
        List<String> orderIds = null;
        try {
            orderIds = clearingMapper.getOrderToUpdate(clearState);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("查询符合调教的订单失败");
        }
        clearState.put("orderIds", splitStr(orderIds));
        //1,更新D_QR_ORDER表
        try {
            clearingMapper.updateQrOrder(clearState);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("更新D_QR_ORDER表失败");
        }
        //2,更新PLATFORM_CLEARING_ORDER表
       /* try {
            clearingMapper.updatePlatformClearingOrder(clearState);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("更新PLATFORM_CLEARING_ORDER表失败");
        }*/
        //3,插入清算数据到数据库
        clearState.put("id", UUID.randomUUID().toString().replace("-", "").toUpperCase());
        try {
            if ("true".equals(clearState.get("isUpdate"))) {
                clearingMapper.updateClearingData(clearState);
            }else {
                clearingMapper.insertClearingData(clearState);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("插入清算数据到数据库失败");
        }
    }

    private String splitStr(List<String> strings) {
        StringBuffer sb = new StringBuffer();
        for (String ct : strings) {
            sb.append("'");
            sb.append(ct);
            sb.append("',");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClearingOrderState(MinShengClearingResponseDTO minShengClearingResponseDTO) throws CustomException {
        try {
            clearingMapper.updateQrOrderByResponse(minShengClearingResponseDTO);
            clearingMapper.updateClearingDataByResponse(minShengClearingResponseDTO);
            /*List<String> orderIds = clearingMapper.getDQrOrderIdToUpdate(minShengClearingResponseDTO.getOrderId());
            minShengClearingResponseDTO.setOrderId(splitStr(orderIds));
            clearingMapper.updatePlatformClearingOrderByResponse(minShengClearingResponseDTO);*/
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("更新清算状态失败");
        }

    }

    @Override
    public Map<String, Long> getClearingParams() throws CustomException {
        try {
            return clearingMapper.getClearingParams();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取清算参数失败");
        }
    }
}
